import { fileURLToPath, URL } from 'node:url'
import { createHtmlPlugin } from 'vite-plugin-html'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { visualizer } from 'rollup-plugin-visualizer'

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import viteCompression from 'vite-plugin-compression'
import { plugin as buildZip } from './plugin/build-zip.js'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'


const getViteEnv = (mode, target) => {
  return loadEnv(mode, process.cwd())[target]
}
const root = process.cwd()

export default defineConfig(({ command, mode }) => {
  let env = null
  const isBuild = command === 'build'

  if (isBuild) {
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: getViteEnv(mode, 'VITE_TITLE')
          }
        }
      }),

      vue(),
      visualizer(),
      createSvgIconsPlugin({
        // 指定要缓存的图标文件夹
        iconDirs: [fileURLToPath(new URL('./src/assets/svg', import.meta.url))],
        // 执行icon name的格式
        symbolId: 'icon-[name]'
      }),
      buildZip(getViteEnv(mode, 'VITE_BUILD_FILLNAME')),
      viteCompression({
        threshold: 1024 * 500, // 对大于500kb的文件进行压缩
        algorithm: 'gzip', // 采用的压缩算法，默认是 gzip
        ext: '.gz' // 生成的压缩包后缀
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@views': fileURLToPath(new URL('./src/views', import.meta.url)),
        '@img': fileURLToPath(new URL('./src/assets/images', import.meta.url)),
        '@com': fileURLToPath(new URL('./src/components', import.meta.url))
      },
      extensions: ['.vue', '.mjs', '.js', '.json', '.node', '.scss']
    },
    base: '/',
    server: {
      host: '0.0.0.0',
      port: 10,
      open: true
    },
    build: {
      outDir: getViteEnv(mode, 'VITE_BUILD_FILLNAME'),
      rollupOptions: {
        output: {
          entryFileNames: 'js/[name]-[hash].js',
          chunkFileNames: 'js/[name]-[hash].js',
          assetFileNames(assetInfo) {
            if (assetInfo.name.endsWith('.css')) {
              return 'css/[name]-[hash].css'
            }
            const imgExts = ['.png', '.jpg', '.jpeg', '.svg', '.gif', '.ico', '.webp']
            if (imgExts.some((ext) => assetInfo.name.endsWith(ext))) {
              return 'image/[name]-[hash][ext]'
            }

            return 'assets/[name]-[hash][ext]'
          }
        }
      },
      terserOptions: {
        minify: 'esbuild',
        compress: {
          //生产环境时移除console
          drop_console: true,
          drop_debugger: true
        }
      },
      esbuild: {
        drop: env.VITE_DELETE_SIGN == 'true' ? ['console', 'debugger'] : []
      }
    }
  }
})
